<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/3/31 11:37
 */

namespace App\Exception\Handler;


use App\Exception\ServiceException;
use App\Traits\ApiResponseTrait;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\Logger\LoggerFactory;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

class ServiceExceptionHandler extends ExceptionHandler
{
    use ApiResponseTrait;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('default');
    }

    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        if($throwable instanceof ServiceException)
        {
            $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
            $this->logger->error($throwable->getTraceAsString());
            $this->stopPropagation();
            $this->setHttpCode(200);
            return $this->fail($throwable->getMessage(),$throwable->getCode());
        }


        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}